package com.codeplay.controller;

import com.codeplay.entity.Chapter;
import com.codeplay.service.ChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/chapters")
@CrossOrigin(origins = "*")
public class ChapterController {

    private final ChapterService chapterService;

    @Autowired
    public ChapterController(ChapterService chapterService) {
        this.chapterService = chapterService;
    }

    @PostMapping
    public ResponseEntity<Chapter> createChapter(@RequestBody Chapter chapter) {
        return ResponseEntity.ok(chapterService.createChapter(chapter));
    }

    @GetMapping("/{id}")
    public ResponseEntity<Chapter> getChapterById(@PathVariable Long id) {
        return ResponseEntity.ok(chapterService.getChapterById(id));
    }

    @GetMapping("/course/{courseId}")
    public ResponseEntity<List<Chapter>> getChaptersByCourseId(@PathVariable Long courseId) {
        return ResponseEntity.ok(chapterService.getChaptersByCourseId(courseId));
    }

    @PutMapping("/{id}")
    public ResponseEntity<Chapter> updateChapter(@PathVariable Long id, @RequestBody Chapter chapter) {
        chapter.setId(id);
        return ResponseEntity.ok(chapterService.updateChapter(chapter));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteChapter(@PathVariable Long id) {
        chapterService.deleteChapter(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/course/{courseId}/next/{currentOrderIndex}")
    public ResponseEntity<Chapter> getNextChapter(
            @PathVariable Long courseId, @PathVariable Integer currentOrderIndex) {
        return ResponseEntity.ok(chapterService.getNextChapter(courseId, currentOrderIndex));
    }

    @GetMapping("/course/{courseId}/previous/{currentOrderIndex}")
    public ResponseEntity<Chapter> getPreviousChapter(
            @PathVariable Long courseId, @PathVariable Integer currentOrderIndex) {
        return ResponseEntity.ok(chapterService.getPreviousChapter(courseId, currentOrderIndex));
    }
} 